#include "patient_appointmentwidget.h"
#include "ui_patient_appointmentwidget.h"
#include "../../network/networkclient.h"
#include "../common/doctordetailwidget.h"
#include "../common/chatwindow.h"
#include <QJsonArray>
#include <QMessageBox>
#include <QDateTime>
#include <QPushButton>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QTime>
#include <QDialog>
#include <QCalendarWidget>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QDebug>

PatientAppointmentWidget::PatientAppointmentWidget(const Patient& patient, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PatientAppointmentWidget),
    m_patient(patient) {
    ui->setupUi(this);
    
    // 设置医生表格
    ui->doctorTable->setColumnCount(9);
    ui->doctorTable->setHorizontalHeaderLabels(
        {"医生ID", "姓名", "职称", "专长", "上班时间", "挂号费用", "单日上限", "已预约", "剩余数"});
    ui->doctorTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->doctorTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    
    // 设置列宽模式：部分固定宽度，部分自适应
    ui->doctorTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    ui->doctorTable->setColumnWidth(0, 70);
    ui->doctorTable->setColumnWidth(1, 100);
    ui->doctorTable->setColumnWidth(2, 120);
    ui->doctorTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch); // 专长列自动拉伸
    ui->doctorTable->setColumnWidth(4, 180);
    ui->doctorTable->setColumnWidth(5, 90);
    ui->doctorTable->setColumnWidth(6, 80);
    ui->doctorTable->setColumnWidth(7, 80);
    ui->doctorTable->setColumnWidth(8, 150); // 操作列加宽
    
    // 隐藏行号列避免乱码
    ui->doctorTable->verticalHeader()->setVisible(false);
    
    // 设置我的预约表格（添加独立的"联系医生"列）
    ui->myAppointmentTable->setColumnCount(7);
    ui->myAppointmentTable->setHorizontalHeaderLabels(
        {"预约ID", "医生姓名", "预约时间", "状态", "症状描述", "操作", "联系医生"});
    ui->myAppointmentTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->myAppointmentTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    
    // 设置列宽模式
    ui->myAppointmentTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    ui->myAppointmentTable->setColumnWidth(0, 80);
    ui->myAppointmentTable->setColumnWidth(1, 120);
    ui->myAppointmentTable->setColumnWidth(2, 150);
    ui->myAppointmentTable->setColumnWidth(3, 120);  // 状态列加宽以显示取消原因
    ui->myAppointmentTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::Stretch); // 症状描述自动拉伸
    ui->myAppointmentTable->setColumnWidth(5, 100); // 操作列宽度
    ui->myAppointmentTable->setColumnWidth(6, 100); // 联系医生列宽度
    
    // 设置行高确保按钮完整显示
    ui->myAppointmentTable->verticalHeader()->setDefaultSectionSize(40);
    
    // 隐藏行号列避免乱码
    ui->myAppointmentTable->verticalHeader()->setVisible(false);
    
    // 使用 UI 文件中定义的选择时间按钮
    m_selectTimeButton = ui->selectTimeButton;
    
    // 初始化默认时间为明天上午8点
    m_selectedDateTime = QDateTime(QDate::currentDate().addDays(1), QTime(8, 0, 0));
    
    // 更新按钮文本
    updateTimeButtonText();
    
    // 连接按钮点击信号
    connect(m_selectTimeButton, &QPushButton::clicked, this, &PatientAppointmentWidget::onSelectTimeButtonClicked);
    
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &PatientAppointmentWidget::onMessageReceived);
    
    // 初始化门诊类型下拉框
    ui->clinicTypeCombo->addItem("全部", "");
    ui->clinicTypeCombo->addItem("普通门诊", "普通门诊");
    ui->clinicTypeCombo->addItem("专家门诊", "专家门诊");
    ui->clinicTypeCombo->addItem("专病门诊", "专病门诊");
    ui->clinicTypeCombo->addItem("急诊", "急诊");
    
    // 连接筛选信号
    connect(ui->clinicTypeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &PatientAppointmentWidget::onFilterChanged);
    connect(ui->searchButton, &QPushButton::clicked,
            this, &PatientAppointmentWidget::onFilterChanged);
    connect(ui->doctorNameEdit, &QLineEdit::returnPressed,
            this, &PatientAppointmentWidget::onFilterChanged);
    
    loadDepartments();
    loadMyAppointments();
}

PatientAppointmentWidget::~PatientAppointmentWidget() {
    delete ui;
}

void PatientAppointmentWidget::on_departmentCombo_currentIndexChanged(int index) {
    if (index >= 0) {
        int departmentId = ui->departmentCombo->currentData().toInt();
        loadDoctors(departmentId);
    }
}

void PatientAppointmentWidget::on_makeAppointmentButton_clicked() {
    int row = ui->doctorTable->currentRow();
    if (row < 0) {
        QMessageBox::warning(this, "提示", "请选择医生");
        return;
    }
    
    // 检查是否还有剩余预约数
    if (row < m_doctors.size()) {
        const Doctor& doctor = m_doctors[row];
        if (doctor.remainingSlots <= 0) {
            QMessageBox::warning(this, "提示", 
                QString("该医生今日预约已满！\n单日上限：%1 人\n已预约：%2 人")
                .arg(doctor.dailyPatientLimit)
                .arg(doctor.bookedCount));
            return;
        }
    }
    
    int doctorId = ui->doctorTable->item(row, 0)->text().toInt();
    QString symptoms = ui->symptomsEdit->toPlainText();
    
    if (symptoms.isEmpty()) {
        QMessageBox::warning(this, "提示", "请填写症状描述");
        return;
    }
    
    // 检查是否选择了有效的时间
    if (!m_selectedDateTime.isValid()) {
        QMessageBox::warning(this, "提示", "请选择有效的预约时间");
        return;
    }
    
    Appointment appointment;
    appointment.patientId = m_patient.id;
    appointment.doctorId = doctorId;
    appointment.appointmentTime = m_selectedDateTime;
    appointment.symptoms = symptoms;
    appointment.status = "待就诊";
    appointment.createTime = QDateTime::currentDateTime();
    
    QJsonObject request = appointment.toJson();
    NetworkClient::instance().sendRequest(MSG_MAKE_APPOINTMENT, request);
}

void PatientAppointmentWidget::on_refreshButton_clicked() {
    loadMyAppointments();
}

void PatientAppointmentWidget::loadDepartments() {
    NetworkClient::instance().sendRequest(MSG_GET_DEPARTMENTS, QJsonObject());
}

void PatientAppointmentWidget::loadDoctors(int departmentId) {
    QJsonObject request;
    request["department_id"] = departmentId;
    
    // 添加门诊类型筛选
    QString clinicType = ui->clinicTypeCombo->currentData().toString();
    if (!clinicType.isEmpty()) {
        request["clinic_type"] = clinicType;
    }
    
    // 添加医生姓名搜索
    QString doctorName = ui->doctorNameEdit->text().trimmed();
    if (!doctorName.isEmpty()) {
        request["doctor_name"] = doctorName;
    }
    
    NetworkClient::instance().sendRequest(MSG_GET_DOCTORS_BY_DEPT, request);
}

void PatientAppointmentWidget::loadMyAppointments() {
    QJsonObject request;
    request["patient_id"] = m_patient.id;
    NetworkClient::instance().sendRequest(MSG_GET_APPOINTMENTS, request);
}

void PatientAppointmentWidget::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_GET_DEPARTMENTS_RESPONSE) {
        if (data["success"].toBool()) {
            QJsonArray departments = data["departments"].toArray();
            ui->departmentCombo->clear();
            for (const QJsonValue& value : departments) {
                QJsonObject dept = value.toObject();
                ui->departmentCombo->addItem(dept["name"].toString(), dept["id"].toInt());
            }
        }
    } else if (type == MSG_GET_DOCTORS_BY_DEPT_RESPONSE) {
        if (data["success"].toBool()) {
            updateDoctorTable(data["doctors"].toArray());
        }
    } else if (type == MSG_MAKE_APPOINTMENT_RESPONSE) {
        if (data["success"].toBool()) {
            QMessageBox::information(this, "成功", "预约成功");
            ui->symptomsEdit->clear();
            loadMyAppointments();
            
            // 重新加载医生列表以更新预约人数
            int currentDeptId = ui->departmentCombo->currentData().toInt();
            if (currentDeptId > 0) {
                loadDoctors(currentDeptId);
            }
        } else {
            QMessageBox::warning(this, "失败", data["error"].toString());
        }
    } else if (type == MSG_GET_APPOINTMENTS_RESPONSE) {
        if (data["success"].toBool()) {
            updateAppointmentTable(data["appointments"].toArray());
        }
    } else if (type == MSG_CANCEL_APPOINTMENT_RESPONSE) {
        if (data["success"].toBool()) {
            QMessageBox::information(this, "成功", "预约已取消");
            // 重新加载预约列表和医生列表
            loadMyAppointments();
            int currentDeptId = ui->departmentCombo->currentData().toInt();
            if (currentDeptId > 0) {
                loadDoctors(currentDeptId);
            }
        } else {
            QMessageBox::warning(this, "失败", data["error"].toString());
        }
    }
}

void PatientAppointmentWidget::updateDoctorTable(const QJsonArray& doctors) {
    ui->doctorTable->setRowCount(0);
    m_doctors.clear();
    
    for (const QJsonValue& value : doctors) {
        QJsonObject doctorJson = value.toObject();
        Doctor doctor = Doctor::fromJson(doctorJson);
        m_doctors.append(doctor);
        
        int row = ui->doctorTable->rowCount();
        ui->doctorTable->insertRow(row);
        
        ui->doctorTable->setItem(row, 0, 
            new QTableWidgetItem(QString::number(doctor.id)));
        ui->doctorTable->setItem(row, 1, 
            new QTableWidgetItem(doctor.realName));
        ui->doctorTable->setItem(row, 2, 
            new QTableWidgetItem(doctor.title));
        ui->doctorTable->setItem(row, 3, 
            new QTableWidgetItem(doctor.specialty));
        ui->doctorTable->setItem(row, 4, 
            new QTableWidgetItem(doctor.workTime));
        ui->doctorTable->setItem(row, 5, 
            new QTableWidgetItem(QString("¥%1").arg(doctor.consultationFee, 0, 'f', 2)));
        ui->doctorTable->setItem(row, 6, 
            new QTableWidgetItem(QString::number(doctor.dailyPatientLimit)));
        ui->doctorTable->setItem(row, 7, 
            new QTableWidgetItem(QString::number(doctor.bookedCount)));
        
        // 设置剩余数的颜色
        QTableWidgetItem* remainingItem = new QTableWidgetItem(QString::number(doctor.remainingSlots));
        if (doctor.remainingSlots <= 0) {
            remainingItem->setForeground(Qt::red);
        } else if (doctor.remainingSlots < 5) {
            remainingItem->setForeground(QColor(255, 140, 0)); // 橙色
        } else {
            remainingItem->setForeground(Qt::darkGreen);
        }
        ui->doctorTable->setItem(row, 8, remainingItem);
    }
}

void PatientAppointmentWidget::updateAppointmentTable(const QJsonArray& appointments) {
    ui->myAppointmentTable->setRowCount(0);
    
    for (const QJsonValue& value : appointments) {
        QJsonObject appointment = value.toObject();
        
        int row = ui->myAppointmentTable->rowCount();
        ui->myAppointmentTable->insertRow(row);
        
        int appointmentId = appointment["id"].toInt();
        QString status = appointment["status"].toString();
        
        ui->myAppointmentTable->setItem(row, 0, 
            new QTableWidgetItem(QString::number(appointmentId)));
        ui->myAppointmentTable->setItem(row, 1, 
            new QTableWidgetItem(appointment["doctor_name"].toString())); // 显示医生姓名
        
        // 格式化预约时间为"日期 时间段"格式
        QString appointmentTimeStr = appointment["appointment_time"].toString();
        QDateTime appointmentTime = QDateTime::fromString(appointmentTimeStr, "yyyy-MM-dd HH:mm:ss");
        if (!appointmentTime.isValid()) {
            appointmentTime = QDateTime::fromString(appointmentTimeStr, Qt::ISODate);
        }
        QString formattedTime;
        if (appointmentTime.isValid()) {
            QString dateStr = appointmentTime.toString("yyyy-MM-dd");
            int hour = appointmentTime.time().hour();
            QString timeSlot = QString("%1:00-%2:00")
                .arg(hour, 2, 10, QChar('0'))
                .arg(hour + 1, 2, 10, QChar('0'));
            formattedTime = QString("%1 %2").arg(dateStr, timeSlot);
        } else {
            formattedTime = appointmentTimeStr; // 如果解析失败，使用原始字符串
        }
        
        ui->myAppointmentTable->setItem(row, 2, 
            new QTableWidgetItem(formattedTime));
        
        // 如果是已取消且有取消原因，显示取消原因
        QString cancelReason = appointment["cancel_reason"].toString();
        QString displayStatus = status;
        if (status == "已取消" && !cancelReason.isEmpty()) {
            displayStatus = QString("%1\n(%2)").arg(status, cancelReason);
        }
        
        ui->myAppointmentTable->setItem(row, 3, 
            new QTableWidgetItem(displayStatus));
        ui->myAppointmentTable->setItem(row, 4, 
            new QTableWidgetItem(appointment["symptoms"].toString()));
        
        // 第5列：操作（取消预约按钮）
        if (status != "已取消" && status != "已完成") {
            QPushButton* cancelBtn = new QPushButton("取消预约");
            cancelBtn->setMinimumHeight(30);
            cancelBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
            cancelBtn->setProperty("appointmentId", appointmentId);
            connect(cancelBtn, &QPushButton::clicked, this, &PatientAppointmentWidget::onCancelAppointmentClicked);
            ui->myAppointmentTable->setCellWidget(row, 5, cancelBtn);
        }
        
        // 第6列：联系医生（独立列，所有状态都显示）
        int doctorId = appointment["doctor_id"].toInt();
        QString doctorName = appointment["doctor_name"].toString();
        
        QPushButton* chatBtn = new QPushButton("联系医生");
        chatBtn->setMinimumHeight(30);
        chatBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        chatBtn->setProperty("doctorId", doctorId);
        chatBtn->setProperty("doctorName", doctorName);
        chatBtn->setStyleSheet(
            "QPushButton { background-color: #07C160; color: white; border-radius: 3px; }"
            "QPushButton:hover { background-color: #06AD56; }");
        connect(chatBtn, &QPushButton::clicked, this, &PatientAppointmentWidget::onChatWithDoctorClicked);
        ui->myAppointmentTable->setCellWidget(row, 6, chatBtn);
    }
}

void PatientAppointmentWidget::on_viewDetailButton_clicked() {
    int row = ui->doctorTable->currentRow();
    if (row < 0) {
        QMessageBox::warning(this, "提示", "请选择医生");
        return;
    }
    showDoctorDetail(row);
}

void PatientAppointmentWidget::on_doctorTable_cellDoubleClicked(int row, int column) {
    Q_UNUSED(column);
    showDoctorDetail(row);
}

void PatientAppointmentWidget::showDoctorDetail(int row) {
    if (row < 0 || row >= m_doctors.size()) {
        return;
    }
    
    const Doctor& doctor = m_doctors[row];
    DoctorDetailWidget* detailWidget = new DoctorDetailWidget(doctor, this);
    detailWidget->setWindowFlags(Qt::Dialog);
    detailWidget->setWindowModality(Qt::ApplicationModal);
    detailWidget->show();
}

void PatientAppointmentWidget::onCancelAppointmentClicked() {
    QPushButton* btn = qobject_cast<QPushButton*>(sender());
    if (!btn) return;
    
    int appointmentId = btn->property("appointmentId").toInt();
    
    // 弹出确认对话框
    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认取消", 
        "确定要取消这个预约吗？", 
        QMessageBox::Yes | QMessageBox::No);
    
    if (reply == QMessageBox::Yes) {
        // 发送取消预约请求
        QJsonObject request;
        request["appointment_id"] = appointmentId;
        NetworkClient::instance().sendRequest(MSG_CANCEL_APPOINTMENT, request);
    }
}

void PatientAppointmentWidget::onChatWithDoctorClicked() {
    QPushButton* btn = qobject_cast<QPushButton*>(sender());
    if (!btn) return;
    
    int doctorId = btn->property("doctorId").toInt();
    QString doctorName = btn->property("doctorName").toString();
    
    // 打开聊天窗口
    ChatWindow* chatWindow = new ChatWindow(m_patient.id, doctorId, doctorName, "医生", this);
    chatWindow->setWindowModality(Qt::ApplicationModal);
    chatWindow->show();
}

void PatientAppointmentWidget::onFilterChanged() {
    // 获取当前选择的科室
    int departmentId = ui->departmentCombo->currentData().toInt();
    if (departmentId > 0) {
        loadDoctors(departmentId);
    }
}

void PatientAppointmentWidget::updateTimeButtonText() {
    QString dateText = m_selectedDateTime.toString("yyyy-MM-dd");
    int hour = m_selectedDateTime.time().hour();
    QString timeSlotText = QString("%1:00-%2:00").arg(hour, 2, 10, QChar('0')).arg(hour + 1, 2, 10, QChar('0'));
    
    m_selectTimeButton->setText(QString("📅 %1 %2").arg(dateText, timeSlotText));
}

void PatientAppointmentWidget::onSelectTimeButtonClicked() {
    // 创建时间选择对话框
    QDialog *dialog = new QDialog(this);
    dialog->setWindowTitle("选择预约时间");
    dialog->resize(400, 450);
    
    QVBoxLayout *layout = new QVBoxLayout(dialog);
    
    // 添加日历控件
    QCalendarWidget *calendar = new QCalendarWidget(dialog);
    calendar->setMinimumDate(QDate::currentDate());
    calendar->setSelectedDate(m_selectedDateTime.date());
    calendar->setGridVisible(true);
    layout->addWidget(calendar);
    
    // 添加时间段选择
    QLabel *timeLabel = new QLabel("选择时间段:", dialog);
    layout->addWidget(timeLabel);
    
    QComboBox *timeSlotCombo = new QComboBox(dialog);
    layout->addWidget(timeSlotCombo);
    
    // 根据选择的日期动态更新时间段（每小时一个时间段）
    auto updateTimeSlots = [timeSlotCombo, calendar]() {
        timeSlotCombo->clear();
        QDate selectedDate = calendar->selectedDate();
        QTime currentTime = QTime::currentTime();
        QDate currentDate = QDate::currentDate();
        
        // 工作时间：8:00-21:00，每小时一个时间段
        for (int hour = 8; hour < 21; ++hour) {
            if (selectedDate == currentDate) {
                // 今天：只显示未过期的时间段
                if (currentTime.hour() < hour) {
                    QString timeSlotText = QString("%1:00-%2:00")
                        .arg(hour, 2, 10, QChar('0'))
                        .arg(hour + 1, 2, 10, QChar('0'));
                    QString timeValue = QString("%1:00:00").arg(hour, 2, 10, QChar('0'));
                    timeSlotCombo->addItem(timeSlotText, timeValue);
                }
            } else {
                // 其他日期：显示所有时间段
                QString timeSlotText = QString("%1:00-%2:00")
                    .arg(hour, 2, 10, QChar('0'))
                    .arg(hour + 1, 2, 10, QChar('0'));
                QString timeValue = QString("%1:00:00").arg(hour, 2, 10, QChar('0'));
                timeSlotCombo->addItem(timeSlotText, timeValue);
            }
        }
        
        if (timeSlotCombo->count() == 0) {
            timeSlotCombo->addItem("今日已无可预约时间段", "");
        }
    };
    
    // 初始化时间段
    updateTimeSlots();
    
    // 日期改变时更新时间段
    connect(calendar, &QCalendarWidget::selectionChanged, updateTimeSlots);
    
    // 添加按钮
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, dialog);
    layout->addWidget(buttonBox);
    
    connect(buttonBox, &QDialogButtonBox::accepted, dialog, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, dialog, &QDialog::reject);
    
    // 显示对话框
    if (dialog->exec() == QDialog::Accepted) {
        QDate selectedDate = calendar->selectedDate();
        QString timeStr = timeSlotCombo->currentData().toString();
        
        if (!timeStr.isEmpty()) {
            QTime selectedTime = QTime::fromString(timeStr, "HH:mm:ss");
            m_selectedDateTime = QDateTime(selectedDate, selectedTime);
            updateTimeButtonText();
        } else {
            QMessageBox::warning(this, "提示", "今天已无可预约时间段，请选择其他日期");
        }
    }
    
    dialog->deleteLater();
}

